Skip to main content

Chapter 27 - Terraform Import

Importing existing resources into Terraform management.

Import - Generating Configuration


This is used to transition infrastructure to Terraform. As a preview, you can generate some configuration using this command: terraform plan -generate-config-out=generated_resources.tf

https://developer.hashicorp.com/terraform/language/import/generating-configuration

Example:


import.tf:

import {
to = azurerm_resource_group.my_aks_rg
id = "/subscriptions/c97afaf5-14ae-40aa-ad2b-3f39120dc8ba/resourceGroups/SoloAKS_RG"
}

image.png

And... the resulting TF configuration block when you run a terraform plan:
image.png

Terraform apply` then imports it as the .tf file exists. Remember .tf files are flattened out and you can copy them into other blocks.

OR....

Create numerous import blocks and run a terraform plan against them all to import multiple resources.

Bad example


It's not 100% perfect. It imported some sort of configuration, however it errored out on parts that will need to be filled in.
image.png

image.png

You can import the resource as normal, run a terraform plan and note the changes and correct as needed. Or pull from the Azure JSON for the resource. Your choice. IT helps.

Importing normally


You can find a terraform import command at the bottom of every resource in the terraform documentation. You can then write your import statement to import into an existing resource block stub.

Example


# terraform import azurerm_resource_group.my_aks_rg /subscriptions/c97afaf5-14ae-40aa-ad2b-3f39120dc8ba/resourceGroups/SoloAKS_RG
# imports into this stub:

resource "azurerm_resource_group" "myrg" {

}